package com.eclipse.e20200128_java8.排序Arrays_sort_Comparator;

import java.util.Arrays;
import java.util.Comparator;
 /*
  * 为什么用"Super"

如果直接用Comparator<T> c 作为参数，第二个参数是"Comparator<? super T> c" <? super T>意味这类型可以是T或者它的父类型。为什么准许父类型。答案是：
这种方法准许为所有的子类使用相同的比较器。以下的示例是明显的:

作者：明翼
链接：https://www.jianshu.com/p/ebf037d54661
来源：简书
著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。
  */
class Animal{
    int size;
}
 
class Dog extends Animal{
    public Dog(int s){
        size = s;
    }
}
 
class Cat extends Animal{
    public Cat(int s){
        size  = s;
    }
}
 
class AnimalSizeComparator implements Comparator<Animal>{
 
    @Override
    public int compare(Animal o1, Animal o2) {
        return o1.size - o2.size;
    }
    //in this way, all sub classes of Animal can use this comparator.
}
 
public class ArraySort {
 
    public static void main(String[] args) {
        Dog d1 = new Dog(2);
        Dog d2 = new Dog(1);
        Dog d3 = new Dog(3);
 
        Dog[] dogArray = {d1, d2, d3};
        printDogs(dogArray);
 
        Arrays.sort(dogArray, new AnimalSizeComparator());  //为什么参数可以只写new AnimalSizeComparator() 因为自己定义了一个类 然后实现了Comparator接口
        printDogs(dogArray);
 
        System.out.println();
 
        //when you have an array of Cat, same Comparator can be used. 
        Cat c1 = new Cat(2);
        Cat c2 = new Cat(1);
        Cat c3 = new Cat(3);
 
        Cat[] catArray = {c1, c2, c3};
        printDogs(catArray);
 
        Arrays.sort(catArray, new AnimalSizeComparator());  
        printDogs(catArray);
    }
 
    public static void printDogs(Animal[] animals){
        for(Animal a: animals)
            System.out.print("size="+a.size + " ");
        System.out.println();
    }
}